Bash Array, Loop and Conditionals

for Loop

1
2
3
4
5
6
7
8
ii=(1 4 15 16 32 40 41 58 61 72 73 74 97);
for i in ${ii[@]}; do
    echo $i;
done
 
for i in {1..12}; do echo $i; done
for i in {1..12..2}; do echo $i; done
for i in `seq 0 12`; do echo $i; done
break, continue
The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle.

case

1
2
3
4
5
6
7
8
case word in
  pattern1)
    list of command
    ;;
  pattern2)
    list of command
    ;;
esac

bash case

while

    while [ -e $trash_dir/$newfile ]; do
		random_suffix=$RANDOM
		newfile=${file}.${random_suffix}
	done

until

opposite to while, it does something repeatedly until the condition is ture.

If conditional

1
2
3
4
5
if COMMANDS ; then
COMMANDS;
[ elif COMMANDS; then COMMANDS ; ]...
[ else COMMANDS; ]
fi

http://www.thegeekstuff.com/2010/06/bash-conditional-expression/

In the above web page, example 6 explains the difference between [ and [[ (single square bracket and double square bracket). The [[ is an enhanced version of [, normally we do NOT need to use [[ unless we want to use globbing feature and etc. In contrast to [ which is a command like "test", [[ is a keyword, and [[ is only recognized in korn and bash.

http://steve-parker.org/sh/test.shtml

-e      exist file
-d      directory exist 
-eq     equal number
-ne     not equal
-gt     a greater than b
-lt     less than
-nt     newer than
-ot     older than
==      same string
!=      not same string
-z      true if string size is zero
=~      regular expression

ps: == only works in bash, run 'bash script.sh' instead of 'sh script.sh'.

1
2
3
4
5
if [ -e chrX.idx ]; then
  echo "index file exist!";
else
  nohup ./segemehl.x -d chrX.fa -x chrX.idx
fi
1
if [ ! -d $outdir ]; then mkdir $outdir; fi

for directory:

1
if [ -d ./doc/ ]; then

Nested If conditionals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if condition
then
    if condition
    then
        .....
        ..
        do this
    else
        ....
        ..
        do this
    fi
else
    ...
    .....
    do this
fi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if [ condition ]
then
        action
elif [ condition2 ]
then
        action2
.
.
.
elif [ condition3 ]
then
 
else
        actionx
fi

Condition and string comparison

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
S1='name'
S2='Name'
if [ $S1 == $S2 ];    # NOTE [with spaces]
then
   echo "$S1 == $S2";
else
   echo "$S1 != $S2 ";
fi
 
if [ -e ./tmp.sh ];
then
  echo "file exist\n";
else
  echo "no file\n";
fi

Array

1
2
3
4
5
6
7
mm="2 4";
dd="random normal X1 link";
for m in $mm; do
  for d in $dd; do
    echo $m.$d;
  done;
done;

or

1
2
3
4
5
6
7
mm=(2 4);
dd=(random normal X1 link);
for m in "${mm[@]}"; do
  for d in "${dd[@]}"; do
    echo $m.$d;
  done;
done;
Homepage
Comments

Hide Comments